/**
 * 
 */
package com.puneet.graphqueries.net;

import java.io.BufferedWriter;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.util.List;

import com.puneet.graphqueries.yamlconfig.Partition;

/**
 * @author puneet
 * 
 */
public class TCPMessageSender {
	private int retries = 3;

	public int getRetries() {
		return retries;
	}

	public void setRetries(int retries) {
		this.retries = retries;
	}

	public int getSecondsToWaitBetweenRetries() {
		return secondsToWaitBetweenRetries;
	}

	public void setSecondsToWaitBetweenRetries(int secondsToWaitBetweenRetries) {
		this.secondsToWaitBetweenRetries = secondsToWaitBetweenRetries;
	}

	private int secondsToWaitBetweenRetries = 1;

	public void sendMessage(String msg, List<Partition> partitions) {
		System.out.println("Sending message:" + msg);
		for (Partition p : partitions) {
			if (!p.isLocal()) {
				for (int i = 0; i < retries; i++) {
					try {
						Socket s = new Socket(p.getServer(), INetConstants.MESSAGE_SEND_RECEIVE_PORT);
						BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
						bw.write(msg);
						bw.close();
						s.close();
						break;
					} catch (Exception e) {
						System.err.println(" Exception while sending message to: " + p.getServer());
						e.printStackTrace();
						try {
							Thread.sleep(secondsToWaitBetweenRetries * 1000);
						} catch (InterruptedException e1) {
							// TODO Auto-generated catch block
							e1.printStackTrace();
						}
					}

				}
			}
		}
	}

	public void sendMessage(String msg, String server) {

		for (int i = 0; i < retries; i++) {
			try {
				Socket s = new Socket(server, 9796);
				BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
				bw.write(msg);
				bw.close();
				s.close();
				break;
			} catch (Exception e) {
				e.printStackTrace();
				try {
					Thread.sleep(secondsToWaitBetweenRetries * 1000);
				} catch (InterruptedException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
			}

		}

	}
}
